package com.wind.cloud.common.config;

import com.alibaba.fastjson.support.spring.GenericFastJsonRedisSerializer;
import org.springframework.boot.autoconfigure.cache.CacheManagerCustomizer;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.serializer.RedisSerializationContext;

import java.time.Duration;

/**
 * cache 配置
 *
 * @author wind.
 */
@Configuration
@EnableCaching
public class CacheConfig implements CacheManagerCustomizer<RedisCacheManager> {

    @Override
    public void customize(RedisCacheManager cacheManager) {
        // 事务提交后才缓存数据
        cacheManager.setTransactionAware(true);
    }

    @Bean
    public RedisCacheConfiguration redisCacheConfiguration() {
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
        // 默认缓存一小时
        return config.entryTtl(Duration.ofHours(1)).computePrefixWith(name -> ("cache:" + name + ":"))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericFastJsonRedisSerializer()));
    }
}
